package com.bulletelc.apollopre.module.user.login;

import com.bulletelc.apollopre.MyApplication;
import com.bulletelc.apollopre.R;
import com.bulletelc.apollopre.constants.GlobalConfig;
import com.bulletelc.apollopre.constants.NetWorkPath;
import com.bulletelc.apollopre.constants.SPKey;
import com.bulletelc.apollopre.framework.BasePresenter;
import com.bulletelc.apollopre.utils.EncryptUtil;
import com.bulletelc.apollopre.utils.SharedPreferencesUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.PostRequest;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * author: lhl
 * date  : 2017/11/09
 * desc  :
 */

public class LoginPresenter extends BasePresenter<LoginContract.View> implements LoginContract.Presenter {

    @Override
    public void start() {

    }

    @Override
    public void stop() {

    }

    @Override
    public void login(String mobile_number, String password, String equipment_id, String unionid) {
        loginImp(mobile_number, password, equipment_id, unionid);
    }

    @Override
    public void getSetting() {
        getSettingImp();
    }

    @Override
    public void weChatEntry(String code) {
        weChatEntryImp(code);
    }

    /**
     * @param mobile_number 手机号
     * @param password      密码
     * @param equipment_id  设备号
     */
    private void loginImp(String mobile_number, String password, String equipment_id, String unionid) {

        org.json.JSONObject objForm = new org.json.JSONObject();
        org.json.JSONObject object = new org.json.JSONObject();
        try {
            object.put("form_type", NetWorkPath.APP_FORM_TYPE);
            objForm.put("mobile_number", mobile_number);
            objForm.put("password", password);
            if (null != equipment_id && equipment_id.length() > 0) {
                objForm.put("equipment_id", equipment_id);
            }
            if (null != unionid) {
                objForm.put("wechat_union_id", unionid);
            }
            objForm.put("signature_encrypt_data", EncryptUtil.sha256(mobile_number));
            object.put("LoginForm", objForm);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        String objStr = object.toString();

        RequestBody body = RequestBody.create(MediaType.parse(GlobalConfig.CONTENT_TYPE_JSON), objStr);

        PostRequest<String> postRequest = OkGo.<String>post(NetWorkPath.POST_LOGIN)
                .upRequestBody(body);

        postRequest.execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                parseResult(response);
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                if (isViewAttached()) {
                    getView().error(response.getException().toString());
                }
            }
        });
    }

    /**
     * 微信授权登陆
     * @param code
     */
    public void weChatEntryImp(String code) {
        String json = "";
        JSONObject object = new JSONObject();
        try {
            object.put("code", code);
            json = object.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody responseBody = RequestBody.create(MediaType.parse(GlobalConfig.CONTENT_TYPE_JSON), json);
        OkGo.<String>post(NetWorkPath.POST_LOGIN_WECHAT_CODE)
                .upRequestBody(responseBody)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseResult(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                    }
                });
    }

    /**
     * 解析login成功返回的数据
     *
     * @param response
     */
    private void parseResult(Response<String> response) {
        try {
            org.json.JSONObject obj = new org.json.JSONObject(response.body().toString());
            org.json.JSONObject meta = (org.json.JSONObject) obj.get("meta");
            String code = (String) meta.get("code");
            if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(code)) {
                org.json.JSONObject data = (org.json.JSONObject) obj.get("data");
                String access_token = (String) data.get("access_token");
                if (isViewAttached()) {
                    SharedPreferencesUtil.putString(MyApplication.getInstance(), SPKey.SP_ACCESS_TOKEN, access_token);
                    SharedPreferencesUtil.putBoolean(MyApplication.getInstance(), SPKey.SP_CHECK_IS_LOGIN, true);
                    MyApplication.setToken(access_token);
                    if (isViewAttached()) {
                        getView().success();
                    }
                }

            } else if (GlobalConfig.HTTP_RESULT_WX_ENTRY.equals(code)) {
                JSONObject extraData = meta.getJSONObject("extraData");
                String unionid = extraData.getString("unionid");
                if (isViewAttached()) {
                    getView().onSuccessWeChatEntry(unionid);
                } else {
                    if (isViewAttached()) {
                        getView().fail((String) meta.get("msg"));
                    }
                }
            } else  {
                if (isViewAttached()) {
                    getView().fail((String) meta.get("msg"));
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
            if (isViewAttached()) {
                getView().error(MyApplication.getInstance().getString(R.string.toast_json_exception));
            }
        }
    }

    /**
     * 获取用户信息
     */
    private void getSettingImp() {
        OkGo.<String>get(NetWorkPath.GET_SETTING)
                .params("access_token", MyApplication.getToken())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        //LogUtil.i(response.body().toString());
                        parseSetting(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        if (isViewAttached()) {
                            getView().onErrorGetSetting(response.getException().toString());
                        }
                    }
                });
    }

    /**
     * 解析数据
     *
     * @param response
     */
    private void parseSetting(Response<String> response) {
        if (response.isSuccessful()) {
            try {
                org.json.JSONObject object = new org.json.JSONObject(response.body().toString());
                JSONObject objMeta = new JSONObject(object.getString("meta"));
                if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(objMeta.getString("code").toString())) {
                    org.json.JSONArray dataArray = object.getJSONArray("data");
                    org.json.JSONObject objSub = new org.json.JSONObject(dataArray.getJSONObject(0).getString("profile"));
                    SharedPreferencesUtil.putString(MyApplication.getInstance(), SPKey.SP_USER_ID, objSub.getString("id"));
                    SharedPreferencesUtil.putString(MyApplication.getInstance(), SPKey.SP_USER_MOBILE_NUMBER, dataArray.getJSONObject(0).getString("mobile_number"));
                    MyApplication.setUserId(objSub.getString("id"));
                    if (isViewAttached()) {
                        getView().onSuccessGetSetting();
                    }
                } else {
                    if (isViewAttached()) {
                        getView().onFailGetSetting(objMeta.getString("msg"));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                if (isViewAttached()) {
                    getView().onErrorGetSetting("数据解释错误");
                }
            }
        } else {
            if (isViewAttached()) {
                getView().onFailGetSetting(response.body().toString());
            }
        }
    }

}
